#include "Thread.hpp"
#include "LockGuard.hpp"

#include <pthread.h>

using namespace ThreadMouble;

const int gnum = 4;
int tickets = 10000;
void route(ThreadData* td)
{
    while (true)
    {
        LockGuard lock(td->_lock);//用线程数据中记录的锁的号码去申请锁
        if (tickets > 0)
        {
            std::cout << td->_name << ":" << tickets << std::endl;
            tickets--;
            usleep(1000);
        }
        else
        {
            break;
        }
    }
}
int main()
{
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex,nullptr);//初始化锁
    std::vector<Thread> threads;
    for (int i = 0; i < gnum; i++)
    {
        std::string name = "Thread-" + std::to_string(i + 1);
        ThreadData* td = new ThreadData(name,mutex);//创建锁数据的对象进行传参
        threads.emplace_back(name, route,td);
        usleep(1000);
    }

    for (auto &thread : threads)
    {
        thread.start();
    }

    for (auto &thread : threads)
    {
        thread.join();
    }

    pthread_mutex_destroy(&mutex);//销毁锁

    return 0;
}